<?php

namespace Frieza\Modules\ConstructionPurchase\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel;
use Doraemon\model\ConstructionPurchase\ConstructionCategory;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use Encore\Admin\Grid;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class CategoryController extends Controller
{
    public function index(Content $content, Request $request)
    {
        $result = ConstructionCategory::selectListByWhere(['status[!]' => ConstructionCategory::STATUS_DELETE, 'ORDER' => ['sort' => 'ASC', 'id' => 'ASC']]);
        $childList = [];
        foreach ($result as $row) {
            if ($row['pid'] > 0) {
                $childList[$row['pid']][] = $row;
            }
        }
        $list = [];
        foreach ($result as $row) {
            if (0 == $row['pid']) {
                $row['child_list'] = $childList[$row['id']] ?? [];
                $list[] = $row;
            }
        }
        $gridModel = new GridDataModel($list);
        $grid = Admin::grid($gridModel,
            function (Grid $grid) {
                $grid->disableFilter();
                $grid->disablePagination();
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->column('id', 'ID')->sort();;
                $grid->column('name', '分类名称');
                $grid->column('status', '状态')->switch([
                    'on' => ['value' => ConstructionCategory::STATUS_NORMAL, 'text' => '展示', 'color' => 'primary'],
                    'off' => ['value' => ConstructionCategory::STATUS_HIDE, 'text' => '隐藏', 'color' => 'default'],
                ]);
                $grid->column('child_list', '关联二级分类')->display(function () {
                    $format = [];
                    if ($this->child_list) {
                        foreach ($this->child_list as $childRow) {
                            $name = $childRow['name'] ?: '空标题 ID:'.$childRow['id'];
                            $url = url('/admin/constructionPurchase/category/index/' . $this->id . '/edit/' . $childRow['id'] . '/edit');
                            $format[] = "<a href='{$url}'>{$name}</a>";
                        }
                    }
                    return $format;
                })->label('default');
            }
        );

        return $content
            ->header('一级分类管理')
            ->breadcrumb(['text' => '一级分类管理'])
            ->row($grid->render());
    }

    public function editFirst(Content $content, Request $request, $id = 0)
    {
        $tab = new Tab();
        $info = [];
        if ($id) {
            $info = ConstructionCategory::getInfoByWhere(['id' => $id]);
        }
        $form = new Form($info);
        $form->hidden('id', 'ID');
        $form->text('name', '一级分类名称')->setWidth(4, 2)->required();
        $form->action(url('admin/constructionPurchase/category/index/saveFirst'));
        $tab->add('基础信息', $form);
        if ($id) {
            $list = ConstructionCategory::selectListByWhere(['pid' => $id, 'status[!]' => ConstructionCategory::STATUS_DELETE, 'ORDER' => ['sort' => 'ASC', 'id' => 'ASC']]);
            $gridModel = new GridDataModel($list);
            $grid = Admin::grid($gridModel,
                function (Grid $grid) {
                    $grid->disableFilter();
                    $grid->disablePagination();
                    $grid->disableExport();
                    $grid->disableRowSelector();
                    $grid->column('id', 'ID')->sort();
                    $grid->column('name', '标题');
                    $grid->column('desc', '描述');
                    $grid->column('cover_img_url', '封面图')->image();
                    $grid->column('style', '样式')->display(function () {
                        return ConstructionCategory::STYLE_TYPE[$this->style];
                    });
                    $grid->column('status', '状态')->switch([
                        'on' => ['value' => ConstructionCategory::STATUS_NORMAL, 'text' => '展示', 'color' => 'primary'],
                        'off' => ['value' => ConstructionCategory::STATUS_HIDE, 'text' => '隐藏', 'color' => 'default'],
                    ]);
                    $grid->column('link', '链接地址')->linkSelect(false);
                }
            );
            $tab->add('二级分类列表', $grid->render(), true);
        }
        $header = sprintf('一级分类%s配置', $info['name'] ? '「' . $info['name'] . '」' : '');
        return $content->header($header)->breadcrumb(
            ['text' => '一级分类管理', 'url' => url('admin/constructionPurchase/category/index')],
            ['text' => '一级分类配置'])
            ->row($tab->render());
    }


    public function saveFirst(Content $content, Request $request)
    {
        $id = $request->input('id', 0);
        $name = $request->input('name', '');
        $data = [
            'name' => $name,
            'pid' => 0,
            'status' => ConstructionCategory::STATUS_NORMAL,
        ];
        if ($id) {
            $id = ConstructionCategory::updateData($data, ['id' => $id]);
        } else {
            $id = ConstructionCategory::addData($data);
        }
        if ($id) {
            $success = new MessageBag([
                'title' => '操作成功'
            ]);
            return redirect(url('/admin/constructionPurchase/category/index'))->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => '操作失败'
            ]);
            return back()->withInput()->with(compact('error'));
        }
    }

    public function delFirst(Content $content, Request $request, $id)
    {
        $data = [
            'status' => ConstructionCategory::STATUS_DELETE
        ];
        $rs = ConstructionCategory::updateData($data, ['pid' => $id]);
        $rs = ConstructionCategory::updateData($data, ['id' => $id]);
        if ($rs) {
            return response()->json([
                'status' => true,
                'message' => "操作成功",
            ]);
        } else {
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
    }

    public function sortFirst(Content $content, Request $request)
    {
        $sortInfo = $request->input('sort', null);
        if ($sortInfo && is_array($sortInfo)) {
            foreach ($sortInfo as $key => $val) {
                foreach ($sortInfo as $key => $val) {
                    ConstructionCategory::updateData(['sort' => $val], ['id' => $key]);
                }
            }
        }
    }

    public function switchFirst(Content $content, Request $request, $firstId)
    {
        $status = $request->input('status', null);
        if (!is_null($status)) {
            $status = $status ? ConstructionCategory::STATUS_NORMAL : ConstructionCategory::STATUS_HIDE;
            $result = ConstructionCategory::updateData(['status' => $status], ['id' => $firstId]);
            if ($result) {
                return response()->json([
                    'status' => true,
                    'message' => "success",
                ]);
            } else {
                return response()->json([
                    'status' => false,
                    'message' => "修改失败",
                ]);
            }
        } else {
            return response()->json([
                'status' => false,
                'message' => "修改失败",
            ]);
        }
    }

    public function editSecond(Content $content, Request $request, $firstId, $secondId = 0)
    {
        $firstInfo = ConstructionCategory::getInfoByWhere(['id' => $firstId]);
        $info = [];
        if ($secondId) {
            $info = ConstructionCategory::getInfoByWhere(['id' => $secondId]);
        } else {
            $info['pid'] = $firstId;
        }
        $form = new Form($info);
        $form->hidden('id', 'ID');
        $form->hidden('pid', 'PID');
        $form->text('name', '标题')->setWidth(4, 2);
        $form->text('desc', '描述')->setWidth(4, 2);
        $form->select('style', '样式')->options(ConstructionCategory::STYLE_TYPE)->default(ConstructionCategory::STYLE_TYPE_ONE)->setWidth(4, 2);
        $form->imgUpload('cover_img', '封面图')->help('封面图必传');
        $form->linkSelect('link', '跳转链接');
        $form->action(url('admin/constructionPurchase/category/index/saveSecond'));
        $header = $firstInfo['name'] . '-二级分类信息';
        return $content->header($header)->breadcrumb(
            ['text' => '一级分类管理', 'url' => url('admin/constructionPurchase/category/index')],
            ['text' => $header])
            ->row($form->render());
    }


    public function saveSecond(Content $content, Request $request)
    {
        $pid = $request->input('pid', 0);
        $id = $request->input('id', 0);
        $name = $request->input('name', '');
        $desc = $request->input('desc', '');
        $style = $request->input('style', '1');
        $coverImg = $request->input('cover_img', '');
        $linkType = $request->input('link_type', '');
        $linkParams = $request->input('link_params', '');

        if ($pid) {
            $data = [
                'pid' => $pid,
                'name' => $name,
                'desc' => $desc,
                'style' => $style,
                'cover_img' => $coverImg,
                'link_type' => $linkType,
                'link_params' => json_encode($linkParams, JSON_UNESCAPED_UNICODE),
                'status' => ConstructionCategory::STATUS_NORMAL,
            ];
            if ($id) {
                $id = ConstructionCategory::updateData($data, ['id' => $id]);
            } else {
                $id = ConstructionCategory::addData($data);
            }
            if ($id) {
                $success = new MessageBag([
                    'title' => '操作成功'
                ]);
                return redirect(url('/admin/constructionPurchase/category/index/' . $pid . '/edit'))->with(compact('success'));
            } else {
                $error = new MessageBag([
                    'title' => '操作失败'
                ]);
                return back()->withInput()->with(compact('error'));
            }
        } else {
            $error = new MessageBag([
                'title' => '不存在的一级分类id'
            ]);
            return back()->withInput()->with(compact('error'));
        }
    }

    public function delSecond(Content $content, Request $request, $firstId, $secondId)
    {
        $data = [
            'status' => ConstructionCategory::STATUS_DELETE
        ];
        $rs = ConstructionCategory::updateData($data, ['id' => $secondId]);
        if ($rs) {
            return response()->json([
                'status' => true,
                'message' => "操作成功",
            ]);
        } else {
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
    }

    public function sortSecond(Content $content, Request $request, $firstId)
    {
        $sortInfo = $request->input('sort', null);
        if ($sortInfo && is_array($sortInfo)) {
            foreach ($sortInfo as $key => $val) {
                foreach ($sortInfo as $key => $val) {
                    ConstructionCategory::updateData(['sort' => $val], ['id' => $key]);
                }
            }
        }
    }


    public function switchSecond(Content $content, Request $request, $firstId, $secondId)
    {
        $status = $request->input('status', null);
        if (!is_null($status) && $secondId > 0) {
            $status = $status ? ConstructionCategory::STATUS_NORMAL : ConstructionCategory::STATUS_HIDE;
            $result = ConstructionCategory::updateData(['status' => $status], ['id' => $secondId]);
            if ($result) {
                return response()->json([
                    'status' => true,
                    'message' => "success",
                ]);
            } else {
                return response()->json([
                    'status' => false,
                    'message' => "修改失败",
                ]);
            }
        } else {
            return response()->json([
                'status' => false,
                'message' => "修改失败",
            ]);
        }
    }
}